package com.camel.base.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.camel.base.config.ExceptionMsgConstants;
import com.camel.base.mapper.ZsQuestionMapper;
import com.camel.base.mapper.ZsSurveyMapper;
import com.camel.base.model.*;
import com.camel.base.model.tem.AnswerSubmit;
import com.camel.base.service.ZsAnswerService;
import com.camel.base.service.ZsProjectService;
import com.camel.base.service.ZsSurveyService;
import com.camel.core.entity.IParams;
import com.camel.core.enums.YesNo;
import com.camel.core.exceptions.CustomException;
import com.camel.core.service.AbstractBaseCommonService;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.validation.constraints.AssertTrue;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.camel.base.utils.ExportExcelUtils.*;

/**
 * @author camel
 */
@Service
public class ZsSurveyServiceImpl extends AbstractBaseCommonService<ZsSurveyMapper, ZsSurvey> implements ZsSurveyService<ZsSurvey> {

    @Autowired
    private ZsSurveyMapper mapper;

    @Autowired
    private ZsQuestionMapper questionMapper;

    @Autowired
    private ZsAnswerService<ZsAnswer> answerService;

    @Autowired
    private ZsProjectService<ZsProject> projectService;

    /**
     * 查询列表
     *
     * @param params
     * @return
     */
    @Override
    public List<ZsSurvey> list(IParams params) {
        return mapper.selectIndex(buildWrapper(params));
    }

    public static String camel2under(String c) {
        String separator = "_";
        c = c.replaceAll("([a-z])([A-Z])", "$1" + separator + "$2").toLowerCase();
        return c;
    }

    @Override
    public XSSFWorkbook getImportTemplate(Integer id) {
        ZsSurvey survey = getById(id);
        List<ZsQuestion> zsQuestions = questionMapper.selectListBySurveyId(id);

        List hearder = new ArrayList<>();
        hearder.add("电话号码");
        hearder.addAll(getKeyFromText(survey.getStartShow()));
        hearder.addAll(getKeyFromText(survey.getEndShow()));
        for (ZsQuestion zsQuestion : zsQuestions) {
            hearder.addAll(getKeyFromText(zsQuestion.getName()));
            for (ZsOption child : zsQuestion.getChildren()) {
                hearder.addAll(getKeyFromText(child.getName()));
            }
        }
        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = wb.createSheet("导入模板");
        CellStyle cellStyle = createCellStyle(wb);
//        cellStyle.setAlignment(HorizontalAlignment.CENTER);
//        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        XSSFRow rowHaead = sheet.createRow(0);
        fillRow(rowHaead, createHeadStyle(wb), hearder);
        return wb;
    }

    public static List<String> getKeyFromText(String text) {
        ArrayList<String> r = new ArrayList<>();
        if (StringUtils.isEmpty(text)) {
            return r;
        }
        int i = text.indexOf("#{");
        if (i > -1) {
            int ie = text.indexOf("}", i);
            if (ie > 0) {
                String substring = text.substring(i + 2, ie);
                r.add(substring);
                r.addAll(getKeyFromText(text.substring(ie + 1, text.length())));
            }
        }
        return r;
    }


    @Override
    public void aswer(List<AnswerSubmit> submits) {
        // 判斷总配额是否打满
        AnswerSubmit questionSubmit = submits.get(0);
        ZsSurvey survey = getById(questionSubmit.getSurveyId());
        if (ObjectUtils.isEmpty(survey)) {
            throw new CustomException(ExceptionMsgConstants.SURVEY_NOT_EXSIT);
        }
        if (ObjectUtils.isEmpty(survey.getCollectNum())) {
            throw new CustomException(ExceptionMsgConstants.SURVEY_HAS_NOT_COLLECTNUM_CONFIG);
        }
        if (isFull(survey)) {
            throw new CustomException(survey.getEndShow());
        }

        // 保存样本
        // 1. 保存一个答案
        // 2. 保存答案详情

    }

    @Override
    public boolean isFull(ZsSurvey survey) {
        if (ObjectUtils.isEmpty(survey.getCollectNum())) {
            throw new CustomException(ExceptionMsgConstants.SURVEY_HAS_NOT_COLLECTNUM_CONFIG);
        }
        return survey.getCollectNum() <= validAnswerNum(survey.getId());
    }

    @Override
    public boolean isAnsweed(Integer surveyId, String phone, String lable) {
        if (StringUtils.isEmpty(lable)) {
            return answerService.count(new QueryWrapper<ZsAnswer>().eq("survey_id", surveyId).eq("phone", phone)) > 0;
        }
        return answerService.count(new QueryWrapper<ZsAnswer>().eq("survey_id", surveyId).eq("phone", phone).eq("label", lable)) > 0;
    }

    @Override
    public ZsAnswer addNewAnswer(List<AnswerSubmit> submits) {
        AnswerSubmit submit = submits.get(0);
        ZsAnswer zsAnswer = new ZsAnswer();
        zsAnswer.setUid(StpUtil.getLoginIdAsInt());
        zsAnswer.setCreateAt(new Date());
        zsAnswer.setCreator(StpUtil.getLoginIdAsInt());
        zsAnswer.setUpdateAt(new Date());
        zsAnswer.setUpdator(StpUtil.getLoginIdAsInt());
        zsAnswer.setSurveyId(submit.getSurveyId());
        zsAnswer.setSeat(submit.getSeat());
        zsAnswer.setValid(YesNo.YES.getValue());
        return null;
    }

    @Override
    public int validAnswerNum(Integer surveyId) {
        return answerService.count(new QueryWrapper<ZsAnswer>()
                .eq("survey_id", surveyId)
                .eq("valid", 1)
                .ne("review_status", 2));
    }

    @Override
    public boolean validSave(ZsSurvey entity) {
        if (ObjectUtils.isEmpty(entity.getProjectId())) {
            if (!StringUtils.isEmpty(entity.getProjectName())) {
                ZsProject project = projectService.getOne(new LambdaQueryWrapper<ZsProject>().eq(ZsProject::getName, entity.getProjectName()));
                if(ObjectUtils.isEmpty(project)) {
                    throw new CustomException("不存在的项目信息！");
                } else {
                    entity.setProjectId(project.getId());
                }
            } else {
                throw new CustomException("项目信息必填不能为空！");
            }
        }
        Assert.notNull(entity.getProjectId(), "项目信息错误或为空");
        return true;
    }

    public static void main(String[] args) {
        String p0000000 = new DecimalFormat("P0000000").format(32);

        System.out.println(p0000000);
    }
}




